<?php
    use think\Db; 
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------

// 应用公共文件
/**
 * 打印
 */
function dd() {
    array_map(function($x) { dump($x); }, func_get_args());
    exit;
}

/**
 * 统一返回信息
 * @param $code
 * @param $data
 * @param $msge
 */
function msg($code, $data, $msg)
{
    return compact('code', 'data', 'msg');
}

/**
 * fly社区返回的数组元素
 * @param $fieldname
 * @return bool
 */
function fmsg($status, $action, $msg)
{
    return compact('status', 'action', 'msg');
}

/*验证表单提交*/
function checksubmit($fieldname){
    $post = request()->param();
    if($post && isset($post[$fieldname])){
        $validate = new \think\Validate([
            ['__token__','require|token','来路错误|请勿重复提交'],
        ]);
        if(!$validate->check($post)){
            request()->token();
            showMessage($validate->getError());
        }
        return true;
    } else {
        return false;
    }
}

/*显示模板*/
function showMessage($msg, $code = 0, $url = '', $data = []){
    if(request()->isAjax()){ //判断是否 AJAX 提交
        echo json_encode(['msg'=>$msg, 'code'=>$code, 'url'=>$url, 'data'=>$data]);
    } else {
        $mgs = '<h3>'.($code ? '操作成功'.$msg : '操作失败'.$msg).'</h3><p>2秒后自动跳转</p>';
        if($url){
            $js = '<script>
				setTimeout(function(){
					window.location.href="'.$url.'";
				},2000);
			</script>';
            //停留2秒
            //跳转JS
        } else {
            $js = '<script>
				setTimeout(function(){
					window.location.href="'.$_SERVER["HTTP_REFERER"].'";
				},2000);
			</script>';
            //停留2秒
            //返回上一页
        }
        echo $mgs.$js;
        exit();
    }
    exit();
}

//返回当前url的前缀是“https”或者“http”
function ishttps(){
    $ishttps = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') || $_SERVER['SERVER_PORT'] == 443;//返回bool
    if($ishttps){
        $ishttps = 'https://';
    }else{
        $ishttps = 'http://';
    }
    return $ishttps;
}

//取缓存
function D($key){
    $data = \app\common\CacheData::get_data($key);
    return $data;
}

/***
 * 重置缓存
 * $key 缓存名称（一般为表名）
 ***/
function reD($key){
    $data = \app\common\CacheData::re_data($key);
    return $data;
}


//判断是否是序列化数据
function is_serialized( $data ) {
    $data = trim( $data );
    if ( 'N;' == $data )
        return true;
    if ( !preg_match( '/^([adObis]):/', $data, $badions ) )
        return false;
    switch ( $badions[1] ) {
        case 'a' :
        case 'O' :
        case 's' :
            if ( preg_match( "/^{$badions[1]}:[0-9]+:.*[;}]\$/s", $data ) )
                return true;
            break;
        case 'b' :
        case 'i' :
        case 'd' :
            if ( preg_match( "/^{$badions[1]}:[0-9.E-]+;\$/", $data ) )
                return true;
            break;
    }
    return false;
}

/***
 *截取字符串长度
 *$string 要截取的字符串
 *$length 长度（安全长度）
 *$dot 修饰符
 ***/
function cutstr($string, $length, $dot = ' ...') {
    if(strlen($string) <= $length) {
        return $string;
    }

    $pre = chr(1);
    $end = chr(1);
    $string = str_replace(array('&amp;', '&quot;', '&lt;', '&gt;'), array($pre.'&'.$end, $pre.'"'.$end, $pre.'<'.$end, $pre.'>'.$end), $string);

    $strcut = '';

    $n = $tn = $noc = 0;
    while($n < strlen($string)) {

        $t = ord($string[$n]);
        if($t == 9 || $t == 10 || (32 <= $t && $t <= 126)) {
            $tn = 1; $n++; $noc++;
        } elseif(194 <= $t && $t <= 223) {
            $tn = 2; $n += 2; $noc += 2;
        } elseif(224 <= $t && $t <= 239) {
            $tn = 3; $n += 3; $noc += 2;
        } elseif(240 <= $t && $t <= 247) {
            $tn = 4; $n += 4; $noc += 2;
        } elseif(248 <= $t && $t <= 251) {
            $tn = 5; $n += 5; $noc += 2;
        } elseif($t == 252 || $t == 253) {
            $tn = 6; $n += 6; $noc += 2;
        } else {
            $n++;
        }

        if($noc >= $length) {
            break;
        }

    }
    if($noc > $length) {
        $n -= $tn;
    }

    $strcut = substr($string, 0, $n);


    $strcut = str_replace(array($pre.'&'.$end, $pre.'"'.$end, $pre.'<'.$end, $pre.'>'.$end), array('&amp;', '&quot;', '&lt;', '&gt;'), $strcut);

    $pos = strrpos($strcut, chr(1));
    if($pos !== false) {
        $strcut = substr($strcut,0,$pos);
    }
    return $strcut.$dot;
}

/***
 *分页函数
 *url 链接，页码数字使用{page}标记
 *page 当前页码
 *pagenum 总页数
 *firsturl 第一页的URL（方便SEO优化 去除多余参数）
 ***/
function pagehtml($url,$page,$pagenum,$firsturl = ''){
    if($pagenum == 1){
        return '';
    }
    if(IS_MOBILE){
        $prevtext = '<';
        $nexttext = '>';
        $class = 'mobile';
        $seepagenum = 8;
    } else {
        $prevtext = '上一页';
        $nexttext = '下一页';
        $class = 'pc';
        $seepagenum = 8;
    }

    $i_2 = $seepagenum/2;
    $i_3 = $page - max($i_2,($seepagenum - ($pagenum - $page)));
    $i_4 = $page + max($i_2,($seepagenum - $page));

    $pagehtml = '<div class="default-'.$class.'-page page cl">';
    if($page > 1){
        $pagehtml .= '<a href="'.str_replace('{page}',($page-1),$url).'" class="page_prev">'.$prevtext.'</a>';
    }

    for($i=1;$i<=$pagenum;$i++){
        $_url = ($i != 1 || !$firsturl) ? str_replace('{page}',$i,$url) : $firsturl;
        $class = $i==$page ? 'class="a"' : '';
        if($pagenum > $seepagenum ){
            if ($page > $i_2 && $i == 1){
                $pagehtml .= '<a href="'.$_url.'"'.$class.'>'.$i.'...</a>';
            } elseif ($page < $pagenum - $i_2  && $i == $pagenum){
                $pagehtml .= '<a href="'.$_url.'"'.$class.'>...'.$i.'</a>';
            } elseif ($i > $i_3 && $i < $i_4) {
                $pagehtml .= '<a href="'.$_url.'"'.$class.'>'.$i.'</a>';
            }
        } else {
            $pagehtml .= '<a href="'.$_url.'"'.$class.'>'.$i.'</a>';
        }
    }
    if($page < $pagenum){
        $pagehtml .= '<a href="'.str_replace('{page}',($page+1),$url).'" class="page_next">'.$nexttext.'</a>';
    }
    $pagehtml .='</div>';
    // yun_dump($pagehtml);
    return $pagehtml;
}

/**
 * 请求接口返回内容
 * @param  string $url [请求的URL地址]
 * @param  string $params [请求的参数]  [$ipost=0: $params = http_build_query(array)  $ipost=1: $params = array]
 * @param  int $ipost [是否采用POST形式]
 * @return  string
 */
function curls($url,$params=false,$ispost=0,$headers=[]){
    $httpInfo = [];
    $ch = curl_init();

    curl_setopt( $ch, CURLOPT_HTTP_VERSION , CURL_HTTP_VERSION_1_1 );
    curl_setopt( $ch, CURLOPT_USERAGENT , 'tdydata' );
    curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT , 60 );
    curl_setopt( $ch, CURLOPT_TIMEOUT , 60);
    curl_setopt( $ch, CURLOPT_RETURNTRANSFER , true );
    curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, true);
    if($headers){
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    }
    if( $ispost ){
        curl_setopt( $ch , CURLOPT_POST , true );
        curl_setopt( $ch , CURLOPT_POSTFIELDS , $params );
        curl_setopt( $ch , CURLOPT_URL , $url );
    }else{
        if( $params ){
            curl_setopt( $ch , CURLOPT_URL , $url.'?'.$params );
        } else {
            curl_setopt( $ch , CURLOPT_URL , $url);
        }
    }
    $response = curl_exec( $ch );
    if ($response === FALSE) {
        //echo "cURL Error: " . curl_error($ch);
        return false;
    }
    $httpCode = curl_getinfo( $ch , CURLINFO_HTTP_CODE );
    $httpInfo = array_merge( $httpInfo , curl_getinfo( $ch ) );
    curl_close( $ch );
    return $response;
}

// 对数组或者字符串进行 stripslashes 处理
function tdy_stripslashes($array){
    if(!is_array($array)){
        return stripslashes($array);
    } else {
        foreach($array as &$v){
            $v = tdy_stripslashes($v);
        }
        return $array;
    }
}

function random_str( $length = 32 ) {
//    $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()-_ []{}<>~`+=,.;:/?|';
    $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
    $password = '';
    for ( $i = 0; $i < $length; $i++ ){
        $password .= $chars[ mt_rand(0, strlen($chars) - 1) ];
    }
    return $password;
}

/**
 * 设备或配置系统参数
 * @param string $name 参数名称
 * @param bool $value 默认是null为获取值，否则为更新
 * @return string|bool
 */
function sysconf($name, $value = null)
{
    static $config = [];
    if ($value !== null) {
        list($config, $data) = [[], ['name' => $name, 'value' => $value]];
        return  Db::name('SysConfig')->where(['name'=>$data['name']])->update(['value'=>$data['value']]);
    }
    if (empty($config)) {
        $config = Db::name('SysConfig')->column('name,value');
    }
    return isset($config[$name]) ? $config[$name] : '';
}

